import 'package:shared_preferences/shared_preferences.dart';
import '../models/user.dart';
import 'user_service.dart';

class AuthService {
  final UserService _userService = UserService();

  // Keys for SharedPreferences
  static const String _isLoggedInKey = 'isLoggedIn';
  static const String _currentUserIdKey = 'currentUserId';
  static const String _currentUsernameKey = 'currentUsername';
  static const String _isAdminKey = 'isAdmin';
  static const String _currentUserAgeKey = 'currentUserAge';
  static const String _currentUserGenderKey = 'currentUserGender';

  // Register a new user
  Future<bool> register(String username, String password, int age, String gender) async {
    try {
      // Check if username already exists
      User? existingUser = await _userService.getUserByUsername(username);
      if (existingUser != null) {
        return false; // Username already exists
      }

      // Determine if this is an admin user (password is 123456)
      bool isAdmin = password == '123456';

      // Create new user
      User newUser = User(
        username: username,
        password: password,
        isAdmin: isAdmin,
        age: age,
        gender: gender,
      );

      // Insert user into database
      await _userService.insertUser(newUser);
      return true;
    } catch (e) {
      print('Registration error: $e');
      return false;
    }
  }

  // Login user
  Future<bool> login(String username, String password) async {
    try {
      bool isAuthenticated = await _userService.authenticate(username, password);

      if (isAuthenticated) {
        User? user = await _userService.getUserByUsername(username);
        if (user != null) {
          // Save login state to SharedPreferences
          SharedPreferences prefs = await SharedPreferences.getInstance();
          await prefs.setBool(_isLoggedInKey, true);
          await prefs.setInt(_currentUserIdKey, user.id!);
          await prefs.setString(_currentUsernameKey, user.username);
          await prefs.setBool(_isAdminKey, user.isAdmin);
          if (user.age != null) await prefs.setInt(_currentUserAgeKey, user.age!);
          if (user.gender != null) await prefs.setString(_currentUserGenderKey, user.gender!);
          return true;
        }
      }
      return false;
    } catch (e) {
      print('Login error: $e');
      return false;
    }
  }

  // Logout user
  Future<void> logout() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_isLoggedInKey, false);
    await prefs.remove(_currentUserIdKey);
    await prefs.remove(_currentUsernameKey);
    await prefs.remove(_isAdminKey);
    await prefs.remove(_currentUserAgeKey);
    await prefs.remove(_currentUserGenderKey);
  }

  // Check if user is logged in
  Future<bool> isLoggedIn() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_isLoggedInKey) ?? false;
  }

  // Get current user ID
  Future<int?> getCurrentUserId() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getInt(_currentUserIdKey);
  }

  // Get current username
  Future<String?> getCurrentUsername() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(_currentUsernameKey);
  }

  // Check if current user is admin
  Future<bool> isCurrentUserAdmin() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_isAdminKey) ?? false;
  }

  // Get current user age
  Future<int?> getCurrentUserAge() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getInt(_currentUserAgeKey);
  }

  // Get current user gender
  Future<String?> getCurrentUserGender() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(_currentUserGenderKey);
  }
}
